package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //Spring框架自身对概念模型接口也提供了一个缺省的实现AntPathMatcher,用于匹配Ant风格的路径
    public final static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resq = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();


        log.info("拦截到请求：{}", uri);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/backend/**",
                "/front/**",
                "/common/**"
        };
        boolean chick = chick(urls, uri);
        //判断请求是否是不需要处理的请求路径
        if (chick) {
            log.info("本次请求不用拦截");
            filterChain.doFilter(req, resq);
            return;
        }
        //判断用户是否登录
        if (req.getSession().getAttribute("employee") != null) {
            log.info("用户已登录id为{}", req.getSession().getAttribute("employee"));
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(req, resq);
            return;
        }
        if (req.getSession().getAttribute("user") != null) {
            log.info("用户已登录id为{}", req.getSession().getAttribute("user"));
            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(req, resq);
            return;
        }

        log.info("用户没有登录");
        resq.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean chick(String[] urls, String uri) {

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
